import { expect } from '@jest/globals';
import * as execa from "execa";
import * as fs from "fs";
import * as path from "path";

import { runHvigorAsync } from '../../common/common';
import { ModuleBuildProfileModifier } from "../../common/modifier/module-build-profile-modifier";
import { PackageJsonModifier } from "../../common/modifier/package-json-modifier";
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    [ModuleTemplateType.StaticLibraryWithC]: 1,
  },
};

const testTaskOption: TestTaskOption = TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).sign(SignType.NoSign).ohpmInstall(IsEnable.Enable).build();

const testCaseFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const projectPackageJsonModifier = new PackageJsonModifier(projectRootPath, '');
  await projectPackageJsonModifier
    .updateDependency("library", "./staticNativeCLibrary")
    .output();
  const buildProfileModifier = new ModuleBuildProfileModifier(projectRootPath, 'staticNativeCLibrary');
  await buildProfileModifier.setBuildOption(
    {
      externalNativeOptions: {
        path: "./src/main/cpp/CMakeLists.txt"
      }
    }
  ).output();
  execa.commandSync('ohpm install --all', {encoding: 'utf-8', cwd: projectRootPath});
  expect(fs.existsSync(path.resolve(projectRootPath, 'oh_modules', 'library'))).toBeTruthy();

  // 执行 entry 模块 构建
  const commands = '--mode module -p module=entry@default -p product=default assembleHap --no-daemon'.split(' ');

  const result = await runHvigorAsync(projectRootPath, commands);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  // 检查是否打包工程下配置的依赖的so文件
  const existSoFromProjectDep = fs.existsSync(path.resolve(projectRootPath, 'entry/build/default/intermediates/libs/default/arm64-v8a/libstaticNativeCLibrary.so'));
  expect(existSoFromProjectDep).toBeTruthy();
};

TestCaseBuilder.builder()
  .caseName('DTS2024093017407')
  .description('测试模块是否收集工程下配置依赖的so文件')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(testTaskOption)
  .testFun(testCaseFun)
  .load();
